package com.suxin.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author Tang
 * @classname ServerNio_1
 * @description [  ]
 * @date 2021/6/9 15:39
 */
@Slf4j
public class ServerIo_1 {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress("127.0.0.1", 8888));

        while (true) {
            System.out.println("等待连接...");
            SocketChannel channel = socketChannel.accept();
            new Thread(() -> {
                ByteBuffer allocate = ByteBuffer.allocate(1024);
                while (true) {
                    int len = 0;
                    try {
                        len = channel.read(allocate);
                        log.info("read finish...");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    allocate.flip();
                    System.out.println("len="+len+",context: " + new String(allocate.array(),0,len));
                    allocate.clear();
                }
            }).start();
        }
    }
}